﻿using LoggingMagic.Injectors;
using LoggingMagic.Injectors.Interfaces;
using Mono.Cecil;

namespace LoggingMagic.AssemlyOperations
{
    internal class MethodProcessor
    {
        private readonly ModuleDefinition _module;
        private readonly IInjectorFactory _injectorFactory;


        public MethodProcessor(ModuleDefinition module, IInjectorFactory injectorFactory)
        {
            _module = module;
            _injectorFactory = injectorFactory;
        }

        public void ProcessMethod(MethodFinder.MethodInfo methodInfo)
        {
            var method = methodInfo.MethodDefinition;
            var ops = new Instructions();
            ops.Nop();

            if (LogWithParameters(methodInfo))
            {
                _injectorFactory.WithParameters.Inject(method, ops);
            }
            else
            {
                _injectorFactory.WithoutParameters.Inject(method, ops);
            }

            ops.InsertInto(method.Body.Instructions);
            ops.Clear();
        }

        private bool LogWithParameters(MethodFinder.MethodInfo methodInfo)
        {
            var ctorArguments = methodInfo.Attribute.ConstructorArguments;

            return ctorArguments.Count >= 1 && ctorArguments[0].Value.Equals(true);
        }
    }
}